package com.idol.service.impl;

import com.idol.dao.AuthCodeMapper;
import com.idol.entity.AuthCode;
import com.idol.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * @author SupremeSir
 * @description
 * @className UserServiceImpl
 * @date 2021/2/15 20:59
 **/
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private AuthCodeMapper authCodeMapper;

    @Override
    public boolean regist(String email, String password, String code) {
        if (StringUtils.isBlank(email) || StringUtils.isBlank(code)) {
            return false;
        }
        Example example = new Example(AuthCode.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("email", email);
        criteria.andEqualTo("code", code);
        List<AuthCode> authCodes = authCodeMapper.selectByExample(example);
        if (authCodes.isEmpty()) {
            return false;
        }
        AuthCode authCode = authCodes.get(0);
        long currentTime = System.currentTimeMillis();
        long createtime = authCode.getCreatetime().getTime();
        long expiretime = authCode.getExpiretime().getTime();
        if (currentTime < createtime || currentTime > expiretime) {
            return false;
        }
        authCode.setPassword(password);
        return authCodeMapper.updateByPrimaryKey(authCode) > 0 ? true : false;
    }

    @Override
    public String login(String email, String password) {
        Example example = new Example(AuthCode.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("email", email);
        criteria.andEqualTo("password", password);
        List<AuthCode> authCodes = authCodeMapper.selectByExample(example);
        if (authCodes.isEmpty()) {
            return null;
        }
        AuthCode authCode = authCodes.get(0);
        return authCode.getEmail();
    }

}
